package com.nowcoder.community.interceptor;/**
 * 功能描述
 *
 * @author 21775
 * @date 2022/09/17  22:05
 */

import com.nowcoder.community.annotation.LoginAnnotation;
import com.nowcoder.community.utils.HostHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 *@ClassName LoginRequire
 *@Description TODO 登录检查拦截器
 *@Author 21775
 *@Date 2022/9/17 22:05
 *@Version 1.0
 */
@Component
public class LoginRequireInterceptor implements HandlerInterceptor {
    @Resource
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            LoginAnnotation loginAnnotation = method.getAnnotation(LoginAnnotation.class);
            if (loginAnnotation != null && hostHolder.getUser() == null) {
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
